package priv.wangy.micro.common.utils.json.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * @author zhangjq
 * @since 2024-04-01
 */
public class CstmJacksonDecimalListHandler extends JsonSerializer<List<Number>> {

    @Override
    public void serialize(List<Number> numbers, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (!CollectionUtils.isEmpty(numbers)) {
            double[] doubles = numbers.stream().mapToDouble(number -> {
                BigDecimal decimal = new BigDecimal(number.toString());
                decimal = decimal.setScale(2, RoundingMode.HALF_UP);
                return decimal.doubleValue();
            }).toArray();
            jsonGenerator.writeArray(doubles, 0, doubles.length);
        }
    }
}
